/*
 * Copyright (c) 2022 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "se_napi_oma_channel.h"

#include <memory>
#include <string>
#include "se_napi_oma_common.h"

namespace OHOS {
namespace SE {
namespace KITS {

thread_local napi_ref NapiSEOmaChannel::constRef_ = nullptr;

napi_value JSOmaChannelClassConstructor(napi_env env, napi_callback_info info)
{
    napi_value thisVar = nullptr;
    napi_get_cb_info(env, info, nullptr, nullptr, &thisVar, nullptr);
    NapiSEOmaChannel* omaJSClass = new NapiSEOmaChannel();

    napi_wrap(
        env, thisVar, omaJSClass,
        [](napi_env env, void* data, void* hint) {
            NapiSEOmaChannel* service = (NapiSEOmaChannel*)data;
            if (service) {
                delete service;
                service = nullptr;
            }
        },
        nullptr,
        nullptr);
    return thisVar;
}

void NapiSEOmaChannel::DefineSEOmaChannelJsClass(napi_env env, napi_value exports)
{
    napi_property_descriptor desc[] = {
        DECLARE_NAPI_FUNCTION("getSession", NapiSEOmaChannel::GetSession),
        DECLARE_NAPI_FUNCTION("Close", NapiSEOmaChannel::Close),
        DECLARE_NAPI_FUNCTION("isBasicChannel", NapiSEOmaChannel::IsBasicChannel),
        DECLARE_NAPI_FUNCTION("isClosed", NapiSEOmaChannel::IsClosed),
        DECLARE_NAPI_FUNCTION("getSelectResponse", NapiSEOmaChannel::GetSelectResponse),
        DECLARE_NAPI_FUNCTION("transmit", NapiSEOmaChannel::Transmit),
    };
    // define JS class SEOmaChannel, JS_Constructor is the callback function
    napi_value constructor = nullptr;
    napi_define_class(env, "SEOmaChannel", NAPI_AUTO_LENGTH, JSOmaChannelClassConstructor,
        nullptr, sizeof(desc)/sizeof(desc[0]), desc, &constructor);
    napi_create_reference(env, constructor, 1, &constRef_);
}

napi_value NapiSEOmaChannel::GetSession(napi_env env, napi_callback_info info)
{
    DebugLog("Enter function NapiSEOmaChannel::GetSession:");
    napi_value result = nullptr;
    napi_value thisVar = nullptr;
    size_t argc = ARGV_NUM_0;
    napi_value argv[] = {nullptr};
    NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
    NapiSEOmaCommon::CheckArgCountAndThrow(env, argc, ARGV_NUM_0);
    // TO-DO:get session by calling native method, throw exception when failed
    int32_t status = SEErrorCode::ERR_NONE;

    if (!NapiSEOmaCommon::CheckSEStatusCodeAndThrow(env, status, "getSession")) {
        return NapiSEOmaCommon::CreateUndefined(env);
    }

    // new instance of JS object
    napi_ref ref = nullptr;
    napi_value constructor = nullptr;
    napi_get_reference_value(env, ref, &constructor);
    napi_new_instance(env, constructor, argc, argv, &result);
    return result;
}

napi_value NapiSEOmaChannel::Close(napi_env env, napi_callback_info info)
{
    DebugLog("Enter function NapiSEOmaChannel::Close:");
    napi_value thisVar = nullptr;
    size_t argc = ARGV_NUM_0;
    napi_value argv[] = {nullptr};
    NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
    NapiSEOmaCommon::CheckArgCountAndThrow(env, argc, ARGV_NUM_0);
    // TO-DO:close channel by call native method, throw exception when failed
    int32_t status = SEErrorCode::ERR_NONE;
    
    if (!NapiSEOmaCommon::CheckSEStatusCodeAndThrow(env, status, "close")) {
        // output error log
    }
    return NapiSEOmaCommon::CreateUndefined(env);
}

napi_value NapiSEOmaChannel::IsBasicChannel(napi_env env, napi_callback_info info)
{
    DebugLog("Enter function NapiSEOmaChannel::IsBasicChannel ");
    napi_value result = nullptr;
    napi_value thisVar = nullptr;
    size_t argc = ARGV_NUM_0;
    napi_value argv[] = {nullptr};
    NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
    NapiSEOmaCommon::CheckArgCountAndThrow(env, argc, ARGV_NUM_0);
    // TO-DO get is basic channel by calling native method, throw exception when faild
    int32_t status = SEErrorCode::ERR_NONE;

    if (!NapiSEOmaCommon::CheckSEStatusCodeAndThrow(env, status, "isBasicChannel")) {
        return NapiSEOmaCommon::CreateUndefined(env);
    }
    napi_get_boolean(env, (status == SEErrorCode::ERR_NONE), &result);
    return result;
}

napi_value NapiSEOmaChannel::IsClosed(napi_env env, napi_callback_info info)
{
    DebugLog("Enter function NapiSEOmaChannel::isClosed ");
    napi_value result = nullptr;
    napi_value thisVar = nullptr;
    size_t argc = ARGV_NUM_0;
    napi_value argv[] = {nullptr};
    NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
    NapiSEOmaCommon::CheckArgCountAndThrow(env, argc, ARGV_NUM_0);
    // TO-DO get is closed by calling native method, throw exception when faild
    int32_t status = SEErrorCode::ERR_NONE;

    if (!NapiSEOmaCommon::CheckSEStatusCodeAndThrow(env, status, "isClosed")) {
        return NapiSEOmaCommon::CreateUndefined(env);
    }
    napi_get_boolean(env, (status == SEErrorCode::ERR_NONE), &result);
    return result;
}

napi_value NapiSEOmaChannel::GetSelectResponse(napi_env env, napi_callback_info info)
{
    DebugLog("Enter function NapiSEOmaChannel::GetSelectResponse:");
    napi_value result = nullptr;
    napi_value thisVar = nullptr;
    size_t argc = ARGV_NUM_0;
    napi_value argv[] = {nullptr};
    NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
    NapiSEOmaCommon::CheckArgCountAndThrow(env, argc, ARGV_NUM_0);

    // TO-DO:get select response by call native method, throw expection when failed
    int32_t status = 0;
    std::vector<int32_t> vec = {1};
    if (!NapiSEOmaCommon::CheckSEStatusCodeAndThrow(env, status, "getSelectResponse")) {
        return NapiSEOmaCommon::CreateUndefined(env);
    }

    // new instance of number array
    NapiSEOmaCommon::Int32VectorToJS(env, vec, result);
    return result;
}

napi_value NapiSEOmaChannel::Transmit(napi_env env, napi_callback_info info)
{
    DebugLog("Enter function NapiSEOmaChannel::Transmit:");
    napi_value thisVar = nullptr;
    size_t argc = ARGV_NUM_2;
    napi_value argv[ARGV_NUM_2] = {nullptr};
    NAPI_CALL(env, napi_get_cb_info(env, info, &argc, argv, &thisVar, nullptr));
    NAPI_ASSERT(env, argc > ARGV_NUM_0, "parameter number error!");
    NAPI_ASSERT(env, argc <= ARGV_NUM_2, "parameter number error!");
    std::unique_ptr<ChannelContext> asyncContext = std::make_unique<ChannelContext>(env);
    if (asyncContext == nullptr) {
        ErrorLog("asyncContext is nullptr");
        return NapiSEOmaCommon::CreateUndefined(env);
    }
    if (!NapiSEOmaCommon::ParseBytesVector(env, asyncContext->command, argv[ARGV_INDEX_0])) {
        ErrorLog("parse int vector failed");
        return NapiSEOmaCommon::CreateUndefined(env);
    }

    if (argc == ARGV_NUM_2) {
        // callback function
        if (NapiSEOmaCommon::IsTargetValueType(env, argv[ARGV_INDEX_1], napi_function)) {
            DebugLog("transmit callback is not null");
            napi_create_reference(env, argv[ARGV_INDEX_1], 1, &(asyncContext->callbackRef));
        }
    }
    return HandleAsyncWork(env, asyncContext.release(), "transmit", NativeTransit, NativeTransitCallBack);
}

napi_value NapiSEOmaChannel::HandleAsyncWork(napi_env env,
                                             AsyncContext *context,
                                             std::string workName,
                                             napi_async_execute_callback execute,
                                             napi_async_complete_callback complete)
{
    DebugLog("HandleAsyncWork start workName = %{public}s", workName.c_str());
    napi_value result = nullptr;
    if (context->callbackRef == nullptr) {
        napi_create_promise(env, &context->deferred, &result);
    } else {
        napi_get_undefined(env, &result);
    }
    napi_value resource = NapiSEOmaCommon::CreateUndefined(env);
    napi_value resourceName = nullptr;
    napi_create_string_utf8(env, workName.data(), NAPI_AUTO_LENGTH, &resourceName);
    napi_create_async_work(env, resource, resourceName, execute, complete, (void *)context, &context->work);
    napi_queue_async_work(env, context->work);
    return result;
}

void NapiSEOmaChannel::NativeTransit(napi_env env, void *data)
{
    DebugLog("Enter function NapiSEOmaChannel::NativeTransit:");
    if (data == nullptr) {
        ErrorLog("NapiSEOmaChannel::NativeTransit data is nullptr");
        return NapiSEOmaCommon::ThrowParameterError(env);
    }
    // TO-DO: call native method
}

void NapiSEOmaChannel::NativeTransitCallBack(napi_env env, napi_status status, void *data)
{
    DebugLog("Enter function NapiSEOmaChannel::NativeTransit:");
    if (data == nullptr) {
        ErrorLog("NapiSEOmaChannel::NativeTransit data is nullptr");
        return NapiSEOmaCommon::ThrowParameterError(env);
    }
    auto asyncContext = (AsyncContext *)data;
    if (asyncContext->deferred != nullptr) {
        // TO-DO: call native method
    } else if (asyncContext->callbackRef != nullptr) {
        napi_value callback = nullptr;
        napi_get_reference_value(env, asyncContext->callbackRef, &callback);
        // TO-DO: call native method
        napi_delete_reference(env, asyncContext->callbackRef);
    }
    napi_delete_async_work(env, asyncContext->work);
    delete asyncContext;
    asyncContext = nullptr;
}
} // namespace KITS
} // namespace SE
} // namespace OHOS
